<?php
/**
* @desc 登录表单处理
* @author kevin.wang
* @date 2015-01-01 12:00:00
**/
class LoginForm extends BaseForm
{
	public $username;
	public $password;
	public $rememberMe;
	private $_user;
	private $_identity;
	//表单规则
	public function rules()
	{
		return array(
			array('username, password', 'required', 'message'=>'用户名或密码不能为空'),
			array('rememberMe', 'boolean', 'message'=>'记住密码输入有误'),
			array('password', 'authenticate', 'message'=>'用户名或密码输入有误'),
		);
	}
	//密码验证
	public function authenticate($attribute,$params)
	{
		if(empty($this->_user)){
			$user = new User();
			$this->_user = $user->userLogin($this->username);
		}
		if($this->_user['password'] != $this->encryPasswd($this->password)){
			$this->addError('password',$params['message']);
		}
	}
	//用户登录
	public function login()
	{
		if(empty($this->_user)){
			$user = new User();
			$this->_user = $user->userLogin($this->username);
		}
		if(!empty($this->_user)){
			$user = new User();
			$user->userLoginCount($this->username);
			$duration = $this->rememberMe ? 3600*24*30 : 0; // 30 days
			$this->_identity = new UserIdentity($this->username,$this->password);
			Yii::app()->user->login($this->_identity,$duration);
			unset($this->_user['password']);
			Yii::app()->session['userinfo'] = json_encode($this->_user);
			return true;
		}else{
			return false;
		}
	}
	//检测用户是否登录
	public function userIsLogin(){
		if(isset(Yii::app()->session['userinfo'])){
			return true;
		}
		return false;
	}
}
